// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using svs.Mobile.BeyondMedia.FeedCore.RSS;

namespace svs.Mobile.BeyondMedia.FeedCore.RSS
{
	class EnclosureDownloader
	{
		#region Data Members

		private Track m_CurrentTrack;
		private static DownloadAgent m_Agent;

		public delegate void OnDownloadCompletedEvent(Track t);
		public delegate void OnDownloadErrorEvent(Track t, Exception ex);
		public delegate void OnDownloadProgressEvent(Track t);
		public delegate void OnDownloadTerminatedEvent(Track t);
		public delegate void OnDownloadStartedEvent(Track t);

		public event OnDownloadCompletedEvent EnclosureDownloadCompleted;
		public event OnDownloadErrorEvent EnclosureDownloadFailed;
		public event OnDownloadProgressEvent EnclosureDownloadProgress;
		public event OnDownloadTerminatedEvent EnclosureDownloadTerminated;
		public event OnDownloadStartedEvent EnclosureDownloadStarted;

		#endregion

		#region Public Properties

		/// <summary>
		/// Track to download
		/// </summary>
		public Track Track
		{
			get { return m_CurrentTrack; }
			set
			{
				m_CurrentTrack = value;
			}
		}

		/// <summary>
		/// True if a download is in progress
		/// </summary>
		public bool IsDownloading
		{
			get
			{
				return (m_Agent != null && m_Agent.IsDownloading);
			}
		}

		/// <summary>
		/// Download statististics from the agent
		/// </summary>
		public DownloadStatistics Statistics
		{
			get
			{
				if(m_Agent != null)
					return m_Agent.Statistics;
				else
					return null;
			}
		}

		#endregion

		#region Public Methods

		public void Start()
		{
			try
			{
				m_Agent = new DownloadAgent(CoreHelper.SafeCreateUri(m_CurrentTrack.Url), m_CurrentTrack.TrackPath, m_CurrentTrack.ParentFeed.Credentials);

				m_Agent.DownloadCompleted += OnDownloadCompleted;
				m_Agent.DownloadStarted += OnDownloadStarted;
				m_Agent.DownloadProgress += OnDownloadProgress;
				m_Agent.DownloadError += OnDownloadError;
				m_Agent.DownloadTerminated += OnDownloadTerminated;

				m_Agent.StartDownload();
			}
			catch(Exception ex)
			{
				CoreHelper.WriteLogEntry(string.Format("Unable to start the download of Url:{0}! Reason: {1}", m_CurrentTrack.Url, ex.Message));
				OnDownloadError(null, ex);
			}
		}

		public void Stop()
		{
			if(m_Agent != null)
				m_Agent.Stop();
		}

		#endregion

		#region Private Methods

		void OnDownloadTerminated(string destination)
		{
			m_CurrentTrack.DownloadStatus = Track.DownloadStatuses.Stopped;
			
			if (EnclosureDownloadTerminated != null)
				EnclosureDownloadTerminated(m_CurrentTrack);
		}

		void OnDownloadError(string destination, Exception ex)
		{
			m_CurrentTrack.DownloadStatus = Track.DownloadStatuses.Error;
			m_CurrentTrack.ParentFeed.DownloadFailed = true;
			
			if (EnclosureDownloadFailed != null)
				EnclosureDownloadFailed(m_CurrentTrack, ex);
		}

		void OnDownloadProgress(string destination, long current, long total)
		{
			m_CurrentTrack.DownloadSize = total;
			m_CurrentTrack.DownloadedPortion = current;
			m_CurrentTrack.DownloadStatus = Track.DownloadStatuses.Downloading;

			if (EnclosureDownloadProgress != null)
				EnclosureDownloadProgress(m_CurrentTrack);
		}

		void OnDownloadStarted(string destination)
		{
			m_CurrentTrack.DownloadStatus = Track.DownloadStatuses.Connecting;
			m_CurrentTrack.ParentFeed.DownloadFailed = false;

			if (EnclosureDownloadStarted != null)
				EnclosureDownloadStarted(m_CurrentTrack);
		}

		void OnDownloadCompleted(string destination, bool hasNewContent)
		{
			if(m_CurrentTrack.IsFullyDownloaded)
				m_CurrentTrack.DownloadStatus = Track.DownloadStatuses.Downloaded;
			else
				m_CurrentTrack.DownloadStatus = Track.DownloadStatuses.Stopped;

			EnclosureDownloadHistory.AddEnclosure(destination);

			if (EnclosureDownloadCompleted != null)
				EnclosureDownloadCompleted(Track);
		}

		#endregion

	}
}